package com.lemo.shiro.realms;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.realm.AuthenticatingRealm;
import org.apache.shiro.util.ByteSource;

public class RealmMD5Salt extends AuthenticatingRealm {

	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken auToken) throws AuthenticationException {
		System.out.println("RealmMD5Salt");
		UsernamePasswordToken token = (UsernamePasswordToken) auToken;
		String username = token.getUsername();

		if ("lee".equals(username)) {
			System.out.println("用户不存在！");
			throw new UnknownAccountException("用户不存在");
		}
		if ("lemo".equals(username)) {
			throw new LockedAccountException("锁户");
		}
		Object principal = username;
		Object credentials = null;
		if ("admin".equals(username)) {
			credentials = "038bdaf98f2037b31f1e75b5b4c9b26e";
		} else if ("user".equals(username)) {
			credentials = "098d2c478e9c11555ce2823231e02ec1";
		}

		ByteSource credentialsSalt = ByteSource.Util.bytes(username);

		String realmName = getName();
		SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(principal, credentials, credentialsSalt,
				realmName);
		return info;
	}

	public static void main(String[] args) {
		int hashIterations = 1024;
		Object salt = ByteSource.Util.bytes("user");
		Object source = "123456";
		String algorithmName = "MD5";
		SimpleHash simpleHash = new SimpleHash(algorithmName, source, salt, hashIterations);
		System.out.println(simpleHash);
	}
}
